import { Injectable } from '@nestjs/common';
import { Response } from 'express';
import { CreateOpenaiDto } from './dto/create-openai.dto';
import { UpdateOpenaiDto } from './dto/update-openai.dto';
import OpenAI from "openai";
import { Server } from "socket.io";
@Injectable()
export class OpenaiService {
  async createChat(req: any, res: Response, createOpenaiDto: CreateOpenaiDto) {
    console.log('Received message:', createOpenaiDto.message);
    
    const openai = new OpenAI({
      baseURL: 'https://api.deepseek.com',
      apiKey: 'sk-d25eda73da4c4d548739a958c33e6aab'
    });

    // 构建消息数组
    const messages = createOpenaiDto.message.map(item => ({
      role: item.name === 'AI' ? 'assistant' as const : 'user' as const,
      content: item.message
    }));

    try {
      // 设置SSE响应头
      res.setHeader('Content-Type', 'text/event-stream');
      res.setHeader('Cache-Control', 'no-cache');
      res.setHeader('Connection', 'keep-alive');
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Headers', 'Cache-Control');

      // 发送连接建立事件
      res.write('data: {"type": "connected", "message": "连接已建立"}\n\n');

      const stream = await openai.chat.completions.create({
        model: 'deepseek-chat',
        messages: messages,
        stream: true,
        temperature: 0.7,
        max_tokens: 1000
      });

      // 监听流式数据的每个块
      for await (const chunk of stream) {
        const content = chunk.choices[0]?.delta?.content;
        if (content) {
          console.log('Streaming chunk:', content);
          
          // 使用SSE格式发送数据
          const sseData = {
            type: 'content',
            content: content,
            timestamp: new Date().toISOString()
          };
          
          res.write(`data: ${JSON.stringify(sseData)}\n\n`);
        }
      }

      // 发送完成事件
      res.write('data: {"type": "done", "message": "对话完成"}\n\n');
      res.end();

    } catch (error) {
      console.error('OpenAI API Error:', error);
      
      // 发送错误事件
      const errorData = {
        type: 'error',
        message: 'AI服务暂时不可用',
        error: error.message
      };
      
      res.write(`data: ${JSON.stringify(errorData)}\n\n`);
      res.end();
    }
  }

  create(createOpenaiDto: CreateOpenaiDto) {
    return 'This action adds a new openai';
  }

  findAll() {
    return `This action returns all openai`;
  }

  findOne(id: number) {
    return `This action returns a #${id} openai`;
  }

  update(id: number, updateOpenaiDto: UpdateOpenaiDto) {
    return `This action updates a #${id} openai`;
  }

  remove(id: number) {
    return `This action removes a #${id} openai`;
  }
}
